// @ts-ignore
import {ElMessage} from 'element-plus/es'
import {Encrypt} from '@/utils/bcryptUtil'
import {userLogin, userLogout, userRegister, userUpdatePassword} from "~/server/userAuth.service";

class UserService {
    public login(username: any, password: any): Promise<void> {
        const userStore = useUserStore()
        let params = new URLSearchParams()
        params.append('username', username)
        params.append('password', Encrypt(password))
        return new Promise((resolve) => {
            return userLogin(params).then(({data}: any) => {
                if (data.flag) {
                    userStore.userInfo = data.data
                    sessionStorage.setItem('token', data.data.token)
                    userStore.token = data.data.token
                    ElMessage({message: '登录成功', type: 'success'})
                    resolve()
                } else {
                    ElMessage({message: data.message, type: 'error'})
                }
            })
        })
    }

    public loginOut() {
        const userStore = useUserStore()
        userLogout().then(({data}: any) => {
            if (data.flag) {
                userStore.userInfo = ''
                userStore.token = ''
                userStore.accessArticles = []
                sessionStorage.removeItem('token')
                ElMessage({message: '登出成功', type: 'success'})
            } else {
                ElMessage({message: data.message, type: 'error'})
            }
        })
    }

    public register(username: any, password: any, nickName: any, code: any): Promise<void> {
        let params = {
            code: code,
            username: username,
            password: password,
            nickName: nickName
        }
        return new Promise((resolve) => {
            return userRegister(params).then(async ({data}: any) => {
                if (data.flag) {
                    ElMessage({message: '注册成功', type: 'success'})
                    await this.login(username, password).then(() => console.log('注册后自动登录'))
                    location.reload()
                    resolve()
                } else {
                    ElMessage({message: data.message, type: 'error'})
                }
            })
        })
    }

    public updatePassword(loginInfo: any): Promise<void> {
        return new Promise((resolve) => {
            return userUpdatePassword(loginInfo).then(({data}: any) => {
                if (data.flag) {
                    ElMessage({message: '修改成功', type: 'success'})
                    resolve()
                } else {
                    ElMessage({message: data.message, type: 'error'})
                }
            })
        })
    }
}

export const userService: UserService = new UserService()
